import cloud from "@lafjs/cloud";
import { resultOk, resultFail, listToTree } from "@/utils";
const menuDbName = "menu";
const roleDbName = "role";
const db = cloud.database();
export default async function (ctx: FunctionContext) {
  // 数据库操作
  if (ctx.user === null) {
    return resultFail("用户未登陆", -2);
  }
  const { data: roles } = await db
    .collection(roleDbName)
    .where({
      name: { $in: ctx.user.roles }
    })
    .field({ menuList: 1 })
    .get();
  let menuList = [];
  roles.map(res => {
    menuList = menuList.concat(res.menuList);
    menuList = menuList.concat(res.menuList);
  });
  menuList = [...new Set(menuList)];
  const r = await cloud
    .database()
    .collection(menuDbName)
    .where({
      _id: { $in: menuList }
    })
    .get();
  const auths = r.data.filter(res => res.type === "F");
  return resultOk(
    listToTree(
      r.data
        .filter(res => res.type !== "F")
        .map(res => {
          return {
            path: res.path,
            parentId: res.parentMenuId,
            name: res.path.replace(/\//g, ""),
            meta: {
              roles: ctx.user.roles,
              title: res.name,
              keepAlive: res.isCache,
              auths: auths
                .filter(auth => auth.parentMenuId === res._id)
                .map(res => {
                  return res.perms;
                })
            },
            _id: res._id,
            parentMenuId: res.parentMenuId
          };
        }),
      "_id",
      "parentMenuId"
    )
  );
}
